import React, { useEffect } from 'react';
import { Button, Col, Form, Row, Card, DatePicker } from 'antd';
import { connect } from 'umi';
import moment from 'moment';
// import { history } from 'umi';
import { QuickForm } from 'vv-frontend-components';
// import request from '@/utils/request';
import QueryPage from '@/components/QueryPage';
import Locale from '@/utils/locale';
import CompanyDepart from '@/components/CompanyDepart';
import updateQuery from '@/utils/formValuesToQuery';
// import { exists } from '@/utils/utils';
import { withRoutePage } from '@/utils/enhanceUtils';
import DateRange from '@/components/DateRange';
import YearPicker from '@/components/YearPicker';
import Ryzs from './Components/Ryzs';
import RzrygbFb from './Components/RzrygbFb';
import RzrygwFb from './Components/RzrygwFb';
import Zzryfx from './Components/Zzryfx';
import Tgryfx from './Components/Tgryfx';
import Lzl from './Components/Lzl';
import Zdlz from './Components/Zdlz';
import Bdlz from './Components/Bdlz';
import styles from './index.less';

const { locale } = new Locale('stat.personnel');
const { MonthPicker } = DatePicker;
// const { Option } = Select;

const Personnel = ({ personnel, form, dispatch, location, match, route }) => {
    const {
        query: {
            companyId,
            departmentId,
            dateType,
            startTime,
            endTime,
            quarter,
            tgryfxDateType,
            tgryfxQuarter,
            tgryfxStartTime,
            tgryfxEndTime
        }
    } = location;
    const { ryzs, rzrygb, rzrygw, lzl, zdlz, bdlz, zztgl, zzyql, tgrytj } = personnel;
    console.log('bdlz初始', bdlz);
    const { getFieldDecorator } = form;
    // const { companyDepart = {} } = form.getFieldsValue();
    const disabledDate = current =>
        current &&
        current >
            moment()
                .subtract(1, 'M')
                .endOf('month');

    // 新入职人员分析
    const entryCount = rzrygb.reduce((prev, cur) => prev + cur.value, 0);
    const fetchEntry = () => {
        const { date = { range: [] }, companyDepart = {} } = form.getFieldsValue();
        // e.preventDefault();
        dispatch({
            type: 'personnel/fetchAllEntry',
            payload: {
                companyId: companyDepart.companyId || '',
                departmentId: companyDepart.departmentId || '',
                startTime: date.range[0] ? date.range[0].format('YYYY-MM-DD 00:00:00') : '',
                endTime: date.range[1] ? date.range[1].format('YYYY-MM-DD 23:59:59') : ''
            }
        });
    };
    // 离职人员分析
    const fetchLeave = () => {
        const { leaveMonth, companyDepart = {} } = form.getFieldsValue();
        dispatch({
            type: 'personnel/fetchAllLeave',
            payload: {
                companyId: companyDepart.companyId || '',
                departmentId: companyDepart.departmentId || '',
                endTime: moment(leaveMonth).format('YYYY-MM-DD')
            }
        });
    };

    // 转正人员分析
    const fetchRegular = () => {
        const { regularMonth, companyDepart = {} } = form.getFieldsValue();
        dispatch({
            type: 'personnel/fetchAllRegular',
            payload: {
                companyId: companyDepart.companyId || '',
                departmentId: companyDepart.departmentId || '',
                endTime: moment(regularMonth).format('YYYY-MM-DD')
            }
        });
    };
    // 调岗人员分析
    const fetchTgryfx = () => {
        const { tgryfxDate = { range: [] }, companyDepart = {} } = form.getFieldsValue();
        dispatch({
            type: 'personnel/fetchTgrytj',
            payload: {
                companyId: companyDepart.companyId || '',
                departmentId: companyDepart.departmentId || '',
                startTime: tgryfxDate.range[0] ? tgryfxDate.range[0].format('YYYY-MM-DD 00:00:00') : '',
                endTime: tgryfxDate.range[1] ? tgryfxDate.range[1].format('YYYY-MM-DD 23:59:59') : ''
            }
        });
    };

    // 人员走势
    const fetchRyzs = () => {
        const { ryzsYear, companyDepart = {} } = form.getFieldsValue();
        dispatch({
            type: 'personnel/fetchRyzs',
            payload: {
                id: companyDepart.departmentId || companyDepart.companyId,
                orgFlag: companyDepart.departmentId ? '0' : '1',
                year: ryzsYear.format('YYYY')
            }
        });
    };

    // 人员走势日期筛选
    const ryzsYearChange = v => {
        form.setFieldsValue({ ryzsYear: v }); // 更新下日期值
        fetchRyzs();
    };

    // 转正人员分析日期筛选
    const regularMonthChange = v => {
        form.setFieldsValue({ regularMonth: v }); // 更新下日期值
        fetchRegular();
    };
    // 离职人员分析日期筛选
    const leaveMonthChange = v => {
        form.setFieldsValue({ leaveMonth: v }); // 更新下日期值
        fetchLeave();
    };
    // 调岗人员分析筛选
    const handleTgryfxSubmit = e => {
        fetchTgryfx();
        const { tgryfxDate = { range: [] }, companyDepart = {} } = form.getFieldsValue();

        updateQuery(match.path, {
            companyId: companyDepart && companyDepart.companyId,
            departmentId: companyDepart && companyDepart.departmentId,
            tgryfxDateType: tgryfxDate.type,
            tgryfxStartTime:
                tgryfxDate.range && tgryfxDate.range[0] ? moment(tgryfxDate.range[0]).format('YYYY-MM-DD') : '',
            tgryfxEndTime:
                tgryfxDate.range && tgryfxDate.range[1] ? moment(tgryfxDate.range[1]).format('YYYY-MM-DD') : '',
            tgryfxQuarter: tgryfxDate.quarter || 1
        });
        e.preventDefault();
    };

    // 页面初始加载--多个图表查找方法
    const fetchList = () => {
        // 各个图块请求
        fetchEntry();
        fetchLeave();
        fetchRegular();
        fetchTgryfx();
        fetchRyzs();
    };
    // 主搜索条件搜索
    const handleSubmit = e => {
        console.log('EE', e);
        e.preventDefault();
        fetchList();
    };
    const config = [
        {
            field: 'companyDepart',
            label: locale('xzgsbm'),
            config: {
                initialValue: {
                    companyId,
                    departmentId
                }
            },
            component: (
                <CompanyDepart
                    customDepartmentRequest={{
                        url: '/api/oa/v1/department/getemployeeanalysetree'
                    }}
                    onlyLevelOne
                    permissionCode={route.code}
                />
            )
        },
        {
            component: (
                <div>
                    <Button type="primary" htmlType="submit">
                        {locale('form.search', false)}
                    </Button>
                </div>
            )
        }
    ];
    const startMonth = moment()
        .subtract(1, 'M')
        .startOf('month');
    const endMonth = moment()
        .subtract(1, 'M')
        .endOf('month');
    const rzryConfig = [
        {
            field: 'date',
            config: {
                initialValue: {
                    range: [
                        typeof startTime === 'undefined' ? startMonth : moment(startTime),
                        typeof endTime === 'undefined' ? endMonth : moment(endTime)
                    ],
                    type: typeof dateType === 'undefined' ? 'month' : dateType,
                    quarter: quarter ? Number(quarter) : 1
                }
            },
            component: (
                <DateRange
                    allowClear={false}
                    toNow={false}
                    dateTypes={[
                        {
                            label: '月',
                            type: 'month'
                        },
                        {
                            label: '季度',
                            type: 'quarter'
                        },
                        {
                            label: '年',
                            type: 'year'
                        }
                    ]}
                />
            )
        },
        {
            component: (
                <div>
                    <Button
                        type="primary"
                        onClick={() => {
                            fetchEntry();
                        }}
                    >
                        {locale('form.search', false)}
                    </Button>
                </div>
            )
        }
    ];

    // 调岗人员分析日期控件配置信息
    const tgryfxConfig = [
        {
            field: 'tgryfxDate',
            config: {
                initialValue: {
                    range: [
                        typeof tgryfxStartTime === 'undefined' ? startMonth : moment(tgryfxStartTime),
                        typeof tgryfxEndTime === 'undefined' ? endMonth : moment(tgryfxEndTime)
                    ],
                    type: typeof tgryfxDateType === 'undefined' ? 'month' : tgryfxDateType,
                    quarter: tgryfxQuarter ? Number(tgryfxQuarter) : 1
                }
            },
            component: (
                <DateRange
                    allowClear={false}
                    toNow={false}
                    dateTypes={[
                        {
                            label: '月',
                            type: 'month'
                        },
                        {
                            label: '季度',
                            type: 'quarter'
                        },
                        {
                            label: '年',
                            type: 'year'
                        }
                    ]}
                />
            )
        },
        {
            component: (
                <div>
                    <Button
                        type="primary"
                        onClick={() => {
                            fetchTgryfx();
                        }}
                    >
                        {locale('form.search', false)}
                    </Button>
                </div>
            )
        }
    ];

    useEffect(() => {
        fetchList();
        return () => {
            dispatch({
                type: 'personnel/clear'
            });
        };
    }, []);

    return (
        <div className={styles.personnelPage}>
            <QueryPage
                style={{ overflow: 'hidden' }}
                className="queryPageSearch"
                background="transparent"
                form={
                    <Row type="flex" className="searchTitle">
                        <Col>
                            <h3>{Locale.set('form.public.title')}</h3>
                        </Col>
                        <Col>
                            <Form layout="inline" onSubmit={handleSubmit}>
                                <QuickForm form={form} config={config} />
                            </Form>
                        </Col>
                    </Row>
                }
            />
            <Card
                className={styles.box}
                bordered={false}
                title={locale('ryzs')}
                extra={
                    <Form layout="inline" className={styles.cardExtraDatepicker}>
                        <Form.Item label="选择年份">
                            {getFieldDecorator('ryzsYear', {
                                initialValue: moment().startOf('year')
                            })(
                                <YearPicker
                                    placeholder="请选择年份"
                                    onChange={ryzsYearChange}
                                    format="YYYY"
                                    allowClear={false}
                                />
                            )}
                        </Form.Item>
                    </Form>
                }
            >
                <Ryzs newLocale={locale} data={ryzs} />
            </Card>
            {/* 入职人员分析 */}
            <div className={styles.rzdiv}>
                <Card
                    bordered={false}
                    className={styles.overflowY}
                    title={
                        <span>
                            新入职人员分析<span className={styles.rzSpan}>新入职员工数：</span>
                            <span>{entryCount}人</span>
                        </span>
                    }
                    headStyle={{ marginTop: '12px' }}
                    extra={
                        <Form layout="inline">
                            <QuickForm form={form} config={rzryConfig} />
                        </Form>
                    }
                >
                    <Row gutter={12}>
                        <Col lg={{ span: 24 }} xl={{ span: 12 }}>
                            <RzrygbFb data={rzrygb} count={entryCount} />
                        </Col>
                        <Col className={styles.relative} lg={{ span: 24 }} xl={{ span: 12 }}>
                            <RzrygwFb data={rzrygw} />
                        </Col>
                    </Row>
                </Card>
            </div>
            <div className={styles.box}>
                <Row gutter={12}>
                    <Col lg={{ span: 24 }} xl={{ span: 12 }} style={{ marginBottom: '24px' }}>
                        {/* 转正人员分析 */}
                        <Card
                            bordered={false}
                            title="转正人员分析"
                            extra={
                                <Form layout="inline" className={styles.cardExtraDatepicker}>
                                    <Form.Item label="选择月份">
                                        {getFieldDecorator('regularMonth', {
                                            initialValue: moment()
                                                .subtract(1, 'M')
                                                .startOf('month')
                                        })(
                                            <MonthPicker
                                                placeholder="请选择月份"
                                                disabledDate={disabledDate}
                                                onChange={regularMonthChange}
                                                format="YYYY-MM"
                                                allowClear={false}
                                            />
                                        )}
                                    </Form.Item>
                                </Form>
                            }
                        >
                            <Zzryfx passData={zztgl} delayData={zzyql} />
                        </Card>
                        {/* 调岗人员分析 */}
                        <Card
                            bordered={false}
                            title="调岗人员分析"
                            style={{ marginTop: '12px' }}
                            extra={
                                <Form
                                    layout="inline"
                                    className={styles.cardExtraDatepicker}
                                    onSubmit={handleTgryfxSubmit}
                                >
                                    <QuickForm form={form} config={tgryfxConfig} />
                                </Form>
                            }
                        >
                            <Tgryfx data={tgrytj} />
                        </Card>
                    </Col>
                    <Col className={styles.relative} lg={{ span: 24 }} xl={{ span: 12 }}>
                        <Card
                            bordered={false}
                            className={styles.overflowY}
                            title="离职人员分析"
                            extra={
                                <Form layout="inline" className={styles.cardExtraDatepicker}>
                                    <Form.Item label="选择月份：">
                                        {getFieldDecorator('leaveMonth', {
                                            initialValue: moment()
                                                .subtract(1, 'M')
                                                .startOf('month')
                                        })(
                                            <MonthPicker
                                                placeholder="请选择月份"
                                                disabledDate={disabledDate}
                                                format="YYYY-MM"
                                                onChange={leaveMonthChange}
                                                allowClear={false}
                                            />
                                        )}
                                    </Form.Item>
                                </Form>
                            }
                        >
                            {/* 离职人员分析 */}
                            <div>
                                <Lzl data={lzl} />
                            </div>
                            <div>
                                <Zdlz data={zdlz} />
                            </div>
                            <div>
                                <Bdlz data={bdlz} />
                            </div>
                        </Card>
                    </Col>
                </Row>
            </div>
        </div>
    );
};

export default withRoutePage(
    connect(({ personnel }) => ({
        personnel
    }))(Form.create()(Personnel))
);
